 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=25 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:22 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Finally and catch
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='catch,exception,finally,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Finally and catch</div>

<div class='main-body'>
 <br>
The <tt>finally</tt> block is used to ensure resources are recovered regardless of any problems that may occur.

<P>There are several variations for using the <tt>finally</tt> block, according to how exceptions are handled.
(See the excellent book <em>The Java Programming Language</em> by Arnold, Gosling, and Holmes for related information.)

<p><b>Style 1</b>
<P>If a method <em>throws</em> all exceptions, then it may use a <tt>finally</tt> with no <tt>catch</tt> :
<br>
<PRE>

<span class='keyword'>import</span> java.io.*;

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> SimpleFinally {
  
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main(String... aArgs) <span class='keyword'>throws</span> IOException {
    simpleFinally(<span class='literal'>"C:&#092;&#092;Temp&#092;&#092;test.txt"</span>);
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> simpleFinally(String aFileName) <span class='keyword'>throws</span> IOException {
    <span class='comment'>//If this line throws an exception, then neither the try block
</span>    <span class='comment'>//nor the finally block will execute.
</span>    <span class='comment'>//That is a good thing, since reader would be null.
</span>    BufferedReader reader = <span class='keyword'>new</span> BufferedReader(<span class='keyword'>new</span> FileReader(aFileName));
    <span class='keyword'>try</span> {
      <span class='comment'>//Any exception in the try block will cause the finally block to execute
</span>      String line = <span class='keyword'>null</span>;
      <span class='keyword'>while</span> ( (line = reader.readLine()) != <span class='keyword'>null</span> ) {
        <span class='comment'>//process the line...
</span>      }
    }
    <span class='keyword'>finally</span> {
      <span class='comment'>//The reader object will never be null here.
</span>      <span class='comment'>//This finally is only entered after the try block is 
</span>      <span class='comment'>//entered. But, it's NOT POSSIBLE to enter the try block 
</span>      <span class='comment'>//with a null reader object.
</span>      reader.close();
    }
  }
}
 
</PRE>
<br>
<b>Style 2</b>
<P>If a method <em>handles</em> all exceptions, then an interesting variation is to nest a 
<tt>try..finally</tt> within a <tt>try..catch</tt>. This style is particularly useful when 
the <tt>finally</tt> block throws the same exceptions as the rest of the code (which is common with 
<tt>java.io</tt> operations.) Although this style may seem slightly complex, it appears
to be superior to alternative styles :
<br>
<PRE>

<span class='keyword'>import</span> java.io.*;
<span class='keyword'>import</span> java.util.logging.*;

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> NestedFinally {
  
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main(String... aArgs) {
    nestedFinally(<span class='literal'>"C:&#092;&#092;Temp&#092;&#092;test.txt"</span>);
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> nestedFinally(String aFileName) {
    <span class='keyword'>try</span> {
      <span class='comment'>//If the constructor throws an exception, the finally block will NOT execute
</span>      BufferedReader reader = <span class='keyword'>new</span> BufferedReader(<span class='keyword'>new</span> FileReader(aFileName));
      <span class='keyword'>try</span> {
        String line = <span class='keyword'>null</span>;
        <span class='keyword'>while</span> ( (line = reader.readLine()) != <span class='keyword'>null</span> ) {
          <span class='comment'>//process the line...
</span>        }
      }
      <span class='keyword'>finally</span> {
        <span class='comment'>//no need to check for null
</span>        <span class='comment'>//any exceptions thrown here will be caught by 
</span>        <span class='comment'>//the outer catch block
</span>        reader.close();
      }
    }
    <span class='keyword'>catch</span>(IOException ex){
      fLogger.severe(<span class='literal'>"Problem occured : "</span> + ex.getMessage());
    }
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> Logger fLogger =
    Logger.getLogger(NestedFinally.<span class='keyword'>class</span>.getPackage().getName())
  ;
}
 
</PRE>
<br>
<b>Style 3</b>
<P>A more verbose style places a <tt>catch</tt> within the <tt>finally</tt>. This style is likely the least desirable, since 
it has the most blocks:
<br>
<PRE>

<span class='keyword'>import</span> java.io.BufferedReader;
<span class='keyword'>import</span> java.io.FileReader;
<span class='keyword'>import</span> java.io.IOException;
<span class='keyword'>import</span> java.util.logging.Logger;

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> CatchInsideFinally {
  
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main(String... aArgs) {
    catchInsideFinally(<span class='literal'>"C:&#092;&#092;Temp&#092;&#092;test.txt"</span>);
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> catchInsideFinally(String aFileName) {
    <span class='comment'>//Declared here to be visible from finally block
</span>    BufferedReader reader = <span class='keyword'>null</span>;
    <span class='keyword'>try</span> {
      <span class='comment'>//if this line fails, finally will be executed, and reader will be null
</span>      reader = <span class='keyword'>new</span> BufferedReader(<span class='keyword'>new</span> FileReader(aFileName));
      String line = <span class='keyword'>null</span>;
      <span class='keyword'>while</span> ( (line = reader.readLine()) != <span class='keyword'>null</span> ) {
        <span class='comment'>//process the line...
</span>      }
    }
    <span class='keyword'>catch</span>(IOException ex){
      fLogger.severe(<span class='literal'>"Problem occured : "</span> + ex.getMessage());
    }
    <span class='keyword'>finally</span> {
      <span class='keyword'>try</span> {
        <span class='comment'>//need to check for null
</span>        <span class='keyword'>if</span> ( reader != <span class='keyword'>null</span> ) {
          reader.close();
        }
      }
      <span class='keyword'>catch</span>(IOException ex){
        fLogger.severe(<span class='literal'>"Problem occured. Cannot close reader : "</span> + ex.getMessage());
      }
    }
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> Logger fLogger =
    Logger.getLogger(CatchInsideFinally.<span class='keyword'>class</span>.getPackage().getName())
  ;
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActiona0d7-2.html?Id=8'>Always close streams</a> <br>
 
  
  <a href='TopicAction693b-2.html?Id=43'>Recovering resources</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='25'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=25 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:22 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
